<template>
  <el-tabs style="margin-left: 10px;" v-model="activeName">
    <el-tab-pane label="课程详情" name="first">
      <el-row>
        <router-link v-if="courseInfo.tid == teacherInfo.id" :to="{path: '/edit', query: {id: courseInfo.id}}">
          <el-button type="primary" style="float:right; margin-right:35%">编辑</el-button>
        </router-link>
        <router-link v-if="courseInfo.tid == teacherInfo.id" to="/course">
          <el-button type="primary" style="float:right; margin-right:15px">直播</el-button>
        </router-link>
      </el-row>
      <br />
      <el-row style="margin-left: 12%">
        <el-tag style="float:left; margin-left:50px">教师详情</el-tag>
        <br />
        <br />
      </el-row>

      <el-row style="margin-left: 5%">
        <el-row>
          <el-avatar
            style="width: 120px; height: 120px;float:left;margin-left:25px"
            :src="imgUrl"
            fit="fill"
          ></el-avatar>
          <el-input
            :readonly="true"
            type="textarea"
            resize="none"
            :rows="6"
            placeholder="这个人很懒，什么都没有留下"
            v-model="teacherInfo.detail"
            style="float:left; margin-left:20px; width:800px"
          ></el-input>
        </el-row>
        <p style="float:left; margin-left:60px">{{ teacherInfo.name }}</p>
      </el-row>
      <br />

      <div>
        <el-tag style="float:left; margin-left: 15%">课程简介</el-tag>
        <div style="float:left;">
          <br />
          <br />
          <el-input
            :readonly="true"
            type="textarea"
            resize="none"
            :rows="6"
            placeholder="本课程暂无简介"
            v-model="courseInfo.introduction"
            style="float:left; margin-left: -8%; width:800px"
          ></el-input>
        </div>
      </div>
    </el-tab-pane>

    <el-tab-pane label="目录" name="second">
      <el-container style="margin-left: 10%">
        <el-main style="padding: 0">
          <el-table style="width: 100%" :data="courseListData">
            <el-table-column prop="date" label="日期" width="180"></el-table-column>
            <el-table-column prop="time" label="时间" width="180"></el-table-column>
            <el-table-column prop="course" label="课程" width="180"></el-table-column>
            <el-table-column prop="state" label="课程状态" width="180"></el-table-column>
           <!-- <el-table-column
              label="课件"
              width="80px">
              <template slot-scope="scope">
                <el-button
                  @click="udCourseFile(scope.$index)"
                  type="text"
                  size="small">
                  {{courseInfo.id == teacherInfo.id ? '上传' : '下载'}}
                </el-button>
              </template>
            </el-table-column> -->
            <el-table-column
              label="课件"
              width="80px">
              <template slot-scope="scope">
              <el-upload
                action="https://jsonplaceholder.typicode.com/posts/"
                :before-upload="beforeUpload"
                v-if="courseInfo.tid == teacherInfo.id">
                <el-tooltip class="item" placement="top-start">
                  <div slot="content">限rar/zip文件<br/>且不超过2MB</div>
                  <el-button type="text" @click="upFlag=true, upIndex = scope.$index">上传</el-button>
                </el-tooltip>
              </el-upload>
              <a :href="courseListData[scope.$index].url"><el-button v-if="!(courseInfo.tid == teacherInfo.id)" :disabled="courseListData[scope.$index].url==null" type="text">下载</el-button></a>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="courseInfo.tid == teacherInfo.id">
            <el-divider ></el-divider>
            <p>添加课程：</p>
            <el-col :span="1" style="margin-left: 10px">
              <el-date-picker
                style="width: 140px"
                v-model="schedule.date"
                type="date"
                placeholder="请选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-col>
            <el-col :span="3" style="margin-left: 9%">
              <el-select style="width: 131px;" v-model="schedule.timeId" placeholder="请选择时间段">
                <el-option
                  v-for="item in courseType"
                  :key="item.index"
                  :label="item.name"
                  :value="item.index"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="3">
              <el-input v-model="schedule.title" placeholder="请输入小标题"></el-input>
            </el-col>
            <el-col :span="3" style="margin-left: 30px">
              <el-button type="primary" round @click="addSchedule">添加</el-button>
            </el-col>
          </div>
        </el-main>
      </el-container>
    </el-tab-pane>

    <el-tab-pane label="评价" name="third" style="margin-left: 10%">
      <el-row v-if="!(courseInfo.tid == teacherInfo.id)">
        <el-input
          type="textarea"
          rows=4
          placeholder="请输入内容"
          resize="none"
          v-model="commentText"
          style="max-width: 30%;"
          >
        </el-input>
        <el-rate
          v-model="commentStar"
          show-score
          :allow-half="true"
          style="margin-top: 10px"
          >
        </el-rate>
        <el-button type="primary" style="margin: -20px 25% 0" @click="onSubmit">提交</el-button>
      </el-row>
      <el-row style="margin: 10px">
        <el-radio v-model="radio" label="1" @click.native="getAllComments">所有评价</el-radio>
        <el-radio v-model="radio" label="2" @click.native="getGoodComments">好评</el-radio>
        <el-radio v-model="radio" label="3" @click.native="getBadComments">差评</el-radio>
      </el-row>
      <el-row style="margin: 10px">
        <h3 style="display: flex; ">
          总评：
          <el-rate
          v-model="favRate.percentage"
          show-score
          disabled
          :allow-half="true"
          >
          </el-rate>
          <!-- <el-progress type="circle" :percentage="favRate.percentage" :width="35"></el-progress> -->
        </h3>
      </el-row>
      <div class="block" style="margin: 10px">
        <div class="radio">
          排序方式：
          <el-radio-group v-model="reverse">
            <el-radio :label="true">倒序</el-radio>
            <el-radio :label="false">正序</el-radio>
          </el-radio-group>
        </div>

        <el-timeline :reverse="reverse" style="margin: 10px">
          <el-timeline-item v-for="(activity, index) in commentData" :key="index" :timestamp="activity.timestamp" >
            <div>
              <el-image v-if="activity.iconUrl != ''" :src="activity.iconUrl"
                    style="margin-bottom: -5px; width: 30px; height: 30px; border-radius: 40px">
                <div slot="error">
                  <img src="http://39.108.10.228/pic/滑稽.jpg" style="margin-bottom: -5px; width: 30px; height: 30px; border-radius: 40px">
                </div>
              </el-image>
              {{activity.name}}
              <p style="margin-left: 5%;" id="comment">{{activity.content}}</p>
              <el-rate
                v-model="activity.value"
                disabled
                show-score
                text-color="#ff9900"
                style="margin-left: 5%;"
              ></el-rate>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
export default {
  name: 'CourseDetails',
  data () {
    return {
      imgUrl: '',
      activeName: 'first',
      radio: '1',
      status: this.$store.state.user.status,
      teacherInfo: {
        id: this.$store.state.user.id,
        name: this.$store.state.user.name,
        detail: ''
      },
      courseInfo: {
        id: '',
        introduction: '',
        tid: ''
      },
      favRate: {
        percentage: 20
      },
      reverse: false,
      commentData: [],
      courseListData: [],
      commentText: '',
      commentStar: 0,
      courseType: [
        { index: 0, name: '10:00-11:00' },
        { index: 1, name: '11:00-12:00' },
        { index: 2, name: '14:00-15:00' },
        { index: 3, name: '15:00-16:00' },
        { index: 4, name: '16:00-17:00' },
        { index: 5, name: '19:00-20:00' },
        { index: 6, name: '20:00-21:00' }
      ],
      schedule: {
        cid: null,
        timeId: null,
        date: null,
        title: ''
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now()
        }
      },
      upFlag: false,
      upIndex: 0
    }
  },
  methods: {
    /** 获取课程详情 */
    getTeacherDetail () {
      this.getRequest('/api/course/detail?id=' + this.courseInfo.id)
        .then(res => {
          // console.log("detailData:", res);
          var data = res.data.data
          this.imgUrl = data.userDetailModel.iconUrl
          this.teacherInfo.name = data.userDetailModel.name
          this.teacherInfo.detail = data.userDetailModel.introduction
          this.courseInfo.introduction = data.info
          this.courseInfo.tid = data.userDetailModel.id
        })
        .catch(res => {
          this.$message.error('获取数据时发生错误，请刷新重试')
        })
    },
    /** 获取课程列表 */
    getTeacherCourseList () {
      this.getRequest('/api/course/detail?id=' + this.courseInfo.id)
        .then(res => {
          var data = res.data.data
          console.log('courseListData', data)
          this.courseListData = []
          for (var i in data.simpleScheduleModels) {
            this.courseListData.push({
              id: data.simpleScheduleModels[i].id,
              date: data.simpleScheduleModels[i].date,
              time: data.simpleScheduleModels[i].timeInfo,
              course: data.simpleScheduleModels[i].title,
              state: data.simpleScheduleModels[i].finished ? '已结束' : '未结束',
              url: data.simpleScheduleModels[i].fileUrl
              // state: new Date(data.simpleScheduleModels[i].date) < Date.now() ? '已结束' : '未结束'
            })
          }
          this.courseListData.sort((a, b) => {
            let aT = new Date(a.date).getTime()
            let bT = new Date(b.date).getTime()
            return aT - bT
          })
        })
        .catch(res => {
          this.$message.error('error')
        })
    },
    /** 获取评论 */
    getAllComments () {
      this.getRequest('/api/comment/getComments?cid=' + this.courseInfo.id + '&offset=0')
        .then(res => {
          var data = res.data.data
          // console.log("commentData::", data);
          this.commentData = []
          for (var i in data) {
            this.commentData.push({
              name: data[i].name,
              iconUrl: data[i].iconUrl,
              timestamp: new Date(data[i].createTime).toLocaleString(),
              content: data[i].content,
              value: data[i].star / 2
            })
          }
        })
        .catch(res => {
          // alert("error")
        })
    },
    getGoodComments () {
      this.getRequest('/api/comment/getGoodComments?cid=' + this.courseInfo.id + '&offset=0')
        .then(res => {
          var data = res.data.data
          // console.log("goodCommentData::", data);
          this.commentData = []
          for (var i in data) {
            this.commentData.push({
              name: data[i].name,
              iconUrl: data[i].iconUrl,
              timestamp: new Date(data[i].createTime).toLocaleString(),
              content: data[i].content,
              value: data[i].star / 2
            })
          }
        })
        .catch(res => {
          this.$message.error('error')
        })
    },
    getBadComments () {
      this.getRequest('/api/comment/getBadComments?cid=' + this.courseInfo.id + '&offset=0')
        .then(res => {
          var data = res.data.data
          // console.log("badCommentData::", data);
          this.commentData = []
          for (var i in data) {
            this.commentData.push({
              name: data[i].name,
              iconUrl: data[i].iconUrl,
              timestamp: new Date(data[i].createTime).toLocaleString(),
              content: data[i].content,
              value: data[i].star / 2
            })
          }
        })
        .catch(res => {
          this.$message.error('error')
        })
    },
    computeFavRate () {
      this.getRequest('/api/comment/computeFavRate?cid=' + this.courseInfo.id)
        .then(res => {
          this.favRate.percentage = parseFloat(res.data.data * 5)
        })
        .catch(res => {
          this.$message.error('error')
        })
    },
    onSubmit () {
      if (!this.commentText) {
        this.$message.info('请输入评论')
      } else if (!this.commentStar) {
        this.$message.info('请打分')
      } else {
        var _this = this
        this.postRequest('/api/comment/putComment', {
          cid: _this.courseInfo.id,
          stars: _this.commentStar * 2,
          content: _this.commentText
        }).then((res) => {
          if (res.data.code == 200) {
            this.$message.success(res.data.msg)
            this.getAllComments()
            this.commentStar = 0
            this.commentText = ''
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }
    },
    addSchedule () {
      if (!this.schedule.date) {
        this.$message.error('开课日期不能为空')
        return false
      }
      if (!this.schedule.title) {
        this.$message.error('课程名称不能为空')
        return false
      }
      if (this.schedule.timeId == null) {
        this.$message.error('开课时间段不能为空')
        return false
      }
      this.schedule.cid = this.courseInfo.id
      this.postRequestByJSON('/api/schedule/add', this.schedule).then((res) => {
        if (res.data.code === 200) {
          this.$message.success('添加课程成功')
          this.schedule.timeId = null
          this.schedule.date = null
          this.schedule.title = ''
          this.getTeacherCourseList()
        } else {
          this.$message.console.error(res.data.msg)
        }
      }).catch((res) => {
        console.error(res)
      })
    },
    beforeUpload (file) {
      var fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (file.size / 1024 / 1024 > 2) {
        this.$message.error('上传文件不能大于2MB')
        return false
      } else if (!(fileType == 'zip' || fileType == 'rar')) {
        this.$message.error('文件必须是rar/zip格式')
        return false
      } else if (this.upFlag) {
        let fd = new FormData()
        fd.append('file', file)
        fd.append('sid', this.courseListData[this.upIndex].id)
        this.uploadFileRequest('/api/schedule/upload', fd).then((res) => {
          this.$message.info(res.data.msg)
          this.upFlag = false
        })
      }
    }

  },
  mounted () {
    // console.log(this.$route.query.id)
    this.courseInfo.id = this.$route.query.id
    this.$nextTick(() => {
      this.getTeacherDetail()
      this.getTeacherCourseList()
      this.getAllComments()
      this.computeFavRate()
    })
  }
}
</script>

<style scoped>
#content {
  width: 65%;
  height: auto;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
  font-size: 14px;
  color: #323232;
  font-family: "微软雅黑";
}
#comment {
  width: 65%;
  height: auto;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
  font-size: 14px;
  color: #303133;
  font-family: "微软雅黑";
}
#userName {
  width: 100%;
  height: auto;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
  font-size: 14px;
  color: #606266;
  font-family: "微软雅黑";
}
.el-table::before{
    left: 0;
    bottom: 0;
    width: 0;
    height: 1px;
}
</style>
